<template>
  <div>
<!--    &lt;!&ndash; 教师专属提示卡片 &ndash;&gt;-->
<!--    <el-alert-->
<!--      v-if="user.role === 'TEACHER'"-->
<!--      title="我的班级管理"-->
<!--      type="info"-->
<!--      :closable="false"-->
<!--      style="margin-bottom: 20px">-->
<!--      <template slot>-->
<!--        <span>您好，{{ user.name }}老师！这里显示您担任班主任的所有班级。</span>-->
<!--      </template>-->
<!--    </el-alert>-->

<!--    &lt;!&ndash; 学生专属提示卡片 &ndash;&gt;-->
<!--    <el-alert-->
<!--      v-if="user.role === 'STUDENT'"-->
<!--      title="我的班级信息"-->
<!--      type="success"-->
<!--      :closable="false"-->
<!--      style="margin-bottom: 20px">-->
<!--      <template slot>-->
<!--        <span>这里是您所在班级的详细信息。</span>-->
<!--      </template>-->
<!--    </el-alert>-->

    <div class="search">
      <el-input placeholder="请输入班级名称" style="width: 200px" v-model="name"></el-input>
      <el-button type="info" plain style="margin-left: 10px" @click="load(1)">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px" @click="reset">重置</el-button>
    </div>

    <div class="operation" v-if="user.role === 'ADMIN'">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <div class="table">
      <el-table 
        :data="tableData" 
        stripe  
        @selection-change="handleSelectionChange"
        :empty-text="getEmptyText()">
        <el-table-column type="selection" width="55" align="center" v-if="user.role === 'ADMIN'"></el-table-column>
        <el-table-column prop="id" label="序号" width="80" align="center" sortable></el-table-column>
        <el-table-column prop="name" label="班级名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="content" label="班级描述" show-overflow-tooltip></el-table-column>
        <el-table-column prop="specialityName" label="所属专业" show-overflow-tooltip></el-table-column>
        <!-- 管理员和学生才显示班主任列，教师不需要看（肯定是自己） -->
        <el-table-column 
          v-if="user.role !== 'TEACHER'" 
          prop="teacherName" 
          label="班主任" 
          show-overflow-tooltip>
        </el-table-column>
        <!-- 学生人数列 -->
        <el-table-column 
          prop="studentCount" 
          label="学生人数" 
          width="100"
          align="center">
          <template v-slot="scope">
            <el-tag type="success" size="small" v-if="scope.row.studentCount > 0">
              {{ scope.row.studentCount }} 人
            </el-tag>
            <el-tag type="info" size="small" v-else>
              0 人
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" :width="user.role === 'ADMIN' ? '260' : '100'" align="center">
          <template v-slot="scope">
            <el-button plain type="success" @click="handleView(scope.row)" size="mini">查看</el-button>
            <el-button plain type="primary" @click="handleEdit(scope.row)" size="mini" v-if="user.role === 'ADMIN'">编辑</el-button>
            <el-button plain type="danger" size="mini" @click=del(scope.row.id) v-if="user.role === 'ADMIN'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total">
        </el-pagination>
      </div>
    </div>


    <el-dialog title="信息" :visible.sync="fromVisible" width="40%" :close-on-click-modal="false" destroy-on-close>
      <el-form label-width="100px" style="padding-right: 50px" :model="form" :rules="rules" ref="formRef">
        <el-form-item prop="name" label="班级名称">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="content" label="班级描述">
          <el-input type="textarea" :rows="5" v-model="form.content" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="collegeId" label="所属专业">
          <el-select v-model="form.specialityId" placeholder="请选择专业" style="width: 100%">
            <el-option v-for="item in specialityData" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="teacherId" label="班主任">
          <el-select v-model="form.teacherId" placeholder="请选择教师" style="width: 100%">
            <el-option v-for="item in teacherData" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看班级学生列表对话框 -->
    <el-dialog :title="'班级学生列表 - ' + viewData.name" :visible.sync="viewVisible" width="70%" :close-on-click-modal="false" destroy-on-close>
      <div class="view-header">
        <el-descriptions :column="3" border size="small">
          <el-descriptions-item label="班级名称">
            <span style="font-weight: bold; color: #409EFF;">{{ viewData.name }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="所属专业">
            <el-tag type="success" size="small">{{ viewData.specialityName || '未设置' }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="班主任">
            <el-tag type="warning" size="small">{{ viewData.teacherName || '未分配' }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <div class="student-list" v-loading="studentLoading">
        <el-table :data="studentList" stripe border style="margin-top: 20px" :empty-text="studentList.length === 0 ? '该班级暂无学生' : '暂无数据'">
          <el-table-column prop="id" label="学号" width="80" align="center"></el-table-column>
          <el-table-column label="头像" width="80" align="center">
            <template v-slot="scope">
              <el-avatar :size="40" :src="scope.row.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"></el-avatar>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="用户名" width="120"></el-table-column>
          <el-table-column prop="name" label="姓名" width="100"></el-table-column>
          <el-table-column prop="collegeName" label="所属学院" show-overflow-tooltip></el-table-column>
          <el-table-column prop="specialityName" label="所属专业" show-overflow-tooltip></el-table-column>
          <el-table-column prop="score" label="学分" width="80" align="center">
            <template v-slot="scope">
              <el-tag type="success" size="small">{{ scope.row.score || 0 }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
        
        <div style="margin-top: 15px; text-align: right; color: #909399;">
          共 <span style="color: #409EFF; font-weight: bold;">{{ studentList.length }}</span> 名学生
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="viewVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "Classes",
  data() {
    return {
      tableData: [],  // 所有的数据
      pageNum: 1,   // 当前的页码
      pageSize: 10,  // 每页显示的个数
      total: 0,
      name: null,
      fromVisible: false,
      viewVisible: false, // 查看对话框显示控制
      form: {},
      viewData: {}, // 查看的班级数据
      studentList: [], // 学生列表
      studentLoading: false, // 学生列表加载状态
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      rules: {
        name: [
          {required: true, message: '请输入专业名称', trigger: 'blur'},
        ],
      },
      ids: [],
      specialityData: [],
      teacherData: []
    }
  },
  created() {
    this.load(1)
    this.loadSpeciality()
    this.loadTeacher()
  },
  methods: {
    getEmptyText() {
      if (this.user.role === 'TEACHER') {
        return '您当前没有担任班主任的班级'
      } else if (this.user.role === 'STUDENT') {
        return '未找到您的班级信息'
      } else {
        return '暂无数据'
      }
    },
    loadSpeciality() {
      this.$request.get('/speciality/selectAll').then(res => {
        if (res.code === '200') {
          this.specialityData = res.data
        } else {
          this.$message.error(res.data)
        }
      })
    },
    loadTeacher() {
      this.$request.get('/teacher/selectAll').then(res => {
        if (res.code === '200') {
          this.teacherData = res.data
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handleAdd() {   // 新增数据
      this.form = {}  // 新增数据的时候清空数据
      this.fromVisible = true   // 打开弹窗
    },
    handleEdit(row) {   // 编辑数据
      this.form = JSON.parse(JSON.stringify(row))  // 给form对象赋值  注意要深拷贝数据
      this.fromVisible = true   // 打开弹窗
    },
    handleView(row) {   // 查看班级学生列表
      this.viewData = JSON.parse(JSON.stringify(row))  // 深拷贝数据
      this.viewVisible = true   // 打开查看弹窗
      this.loadStudentList(row.id)  // 加载该班级的学生列表
    },
    loadStudentList(classId) {  // 加载学生列表
      this.studentLoading = true
      this.studentList = []
      this.$request.get('/student/selectAll', {
        params: {
          classId: classId
        }
      }).then(res => {
        this.studentLoading = false
        if (res.code === '200') {
          this.studentList = res.data || []
        } else {
          this.$message.error(res.msg)
        }
      }).catch(() => {
        this.studentLoading = false
      })
    },
    save() {   // 保存按钮触发的逻辑  它会触发新增或者更新
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.$request({
            url: this.form.id ? '/classes/update' : '/classes/add',
            method: this.form.id ? 'PUT' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === '200') {  // 表示成功保存
              this.$message.success('保存成功')
              this.load(1)
              this.fromVisible = false
            } else {
              this.$message.error(res.msg)  // 弹出错误的信息
            }
          })
        }
      })
    },
    del(id) {   // 单个删除
      this.$confirm('您确定删除吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/classes/delete/' + id).then(res => {
          if (res.code === '200') {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    handleSelectionChange(rows) {   // 当前选中的所有的行数据
      this.ids = rows.map(v => v.id)   //  [1,2]
    },
    delBatch() {   // 批量删除
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      this.$confirm('您确定批量删除这些数据吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/classes/delete/batch', {data: this.ids}).then(res => {
          if (res.code === '200') {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    load(pageNum) {  // 分页查询
      if (pageNum) this.pageNum = pageNum
      this.$request.get('/classes/selectPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
        }
      }).then(res => {
        this.tableData = res.data?.list
        this.total = res.data?.total
      })
    },
    reset() {
      this.name = null
      this.load(1)
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
  }
}
</script>

<style scoped>
.view-header {
  margin-bottom: 10px;
}

/* 自定义描述列表样式 */
.view-header >>> .el-descriptions-item__label {
  font-weight: 600;
  color: #606266;
  background-color: #f5f7fa;
}

.view-header >>> .el-descriptions-item__content {
  color: #303133;
}

/* 学生列表容器 */
.student-list {
  min-height: 200px;
}

/* 对话框样式优化 */
.el-dialog__header {
  background-color: #f5f7fa;
  padding: 20px;
}

.el-dialog__title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

/* 头像样式 */
.el-avatar {
  border: 2px solid #f0f0f0;
}
</style>
